<?php
/* ========================================
 * --------------------
 *  SelectQuery.php
 * --------------------
 * Created on 30.03.2010
 * ========================================
 * $Revision: $
 * $Author: Dmitry Boycov
 * $HeadURL: $
 * $Id: $
 * ========================================
 * Changes ["date: description (who)"]:
 *
 * 30.03.2010: Original version (WHo)
 * 15:19:50: Time
 */

require_once("include/bd/Query.php");
require_once("include/bd/Criteria.php");

class SelectQuery  extends Query{

	/**
	 * array(field1, array(field2, aliases), ....)
	 * if fields is null then * 
	 */
	private $fields = null;

	/**
	 * array(criteria1, criteria2,...)
	 */
	private $conditions = null;

	private $join = null;
	private $limit = null;
	private $start = null;
	private $orderBy = null;
	private $sort = null;
	private $groupBy = null;
	private $SQL_NULL = "NULL";

	//private $union = null;
	//private $subQuery = null;

	public function __construct($table,$fields,$conditions){
		parent::__construct($table);
		$this->fields = $fields;
		$this->conditions = $conditions;
	}

	public function addField($field,$aliases = null){
		if($this->fields == null){
			$this->fields = array();
		}
		if(!is_null($field) && is_string($field)){
			if(is_null($aliases)){
				array_push($this->fields, $field);
			}else{
				array_push($this->fields, array($field,$aliases));
			}
		}
	}

	public function addCondition($field,$operator ,$value = null){
		if(is_null($field) || is_null($operator)) return;
		if($this->conditions == null){
			$this->conditions = array();
		}
		if(is_null($value)){
				$value = $this->SQL_NULL;
		}
		array_push($this->conditions, new Criteria($field,$operator ,$value));
	}

	private function generateFieldsStr(){
		if(is_null($this->fields) || empty($this->fields)){
			return '*';
		};
		$f = '';
		foreach($this->fields as $k=>$v){
			if(is_array($v)){
				$f.=$this->escape($v[0])." as ".$this->escape($v[1]).", ";
			}else{
				$f.=$this->escape($v).", ";
			}
		}
		return rtrim($f,', ');
	}

	private function generateWhereStr(){
	}

	public function execute(){
		if(is_null($this->table) || $this->table=='') return '';
		$f = $this->generateFieldsStr();
		$w = $this->generateWhereStr();

		$v=''; $n='';
		$q="SELECT ".$f." FROM `".$this->table."` ";
//		foreach($this->data as $key=>$val) {
//			$n.="`$key`, ";
//			if(strtolower($val)=='null') $v.="NULL, ";
//			elseif(strtolower($val)=='now()') $v.="NOW(), ";
//			else $v.= "'".$this->escape($val)."', ";
//		}
//		$q .= "(". rtrim($n, ', ') .") VALUES (". rtrim($v, ', ') .");";
		return $q;
	}

}
